<script setup lang="ts">
import type { FormRules } from 'element-plus'
import type { AccountResetPwdCmd } from '@/apis/system/accountApi'
import { reactive, ref } from 'vue'
import { accountApi, AccountResetTypes } from '@/apis/system/accountApi'
import { useForm } from '@/composables/useForm'

const dialogVisible = ref(false)
const formData = ref<AccountResetPwdCmd>()

const { formRef, formLoading, submitForm } = useForm(async () => {
  await accountApi.resetPwd(formData.value!)
  dialogVisible.value = false
  ElMessage.success('密码重置成功,请通知账户及时修改密码')
})

const rules = reactive<FormRules<AccountResetPwdCmd>>({
  resetType: [
    { required: true, message: '请选择重置方式', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-z0-9!@#$%^&]{8,32}$/i, message: '密码必须是数字，大小字母和特殊字符(!@#$%^&]),长度8～32', trigger: 'blur' },
  ],
})

function open(accountId: number) {
  formData.value = { accountId, type: 'LOGIN', resetType: 'RANDOM' }
  dialogVisible.value = true
}

defineExpose({ open })
</script>

<template>
  <el-dialog
    v-if="formData"
    v-model="dialogVisible"
    title="重置登录密码"
    width="520"
    destroy-on-close
    draggable
  >
    <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
      <el-alert title="请注意：重置的密码为临时密码,有效期为30分钟，需要及时修改密码！" type="warning" :closable="false" />
      <el-form-item label="重置方式" prop="resetType" class="mt-4">
        <el-segmented v-model="formData.resetType" :options="[...AccountResetTypes]" />
      </el-form-item>
      <el-form-item v-if="formData.resetType === 'CUSTOM'" label="重置密码" prop="password">
        <el-input v-model="formData.password" show-password type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="formLoading" @click="submitForm">
          重置密码
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
